package com.lora.service.impl;

import com.acooly.core.utils.Dates;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.lora.dao.EquimentDao;
import com.lora.dto.EquipmentDto;
import com.lora.entity.Alarm;
import com.lora.entity.AlarmList;
import com.lora.enums.EquipmentEnum;
import com.lora.judge.CheckUtil;
import com.lora.service.*;
import com.lora.websocket.message.WebSockerSender;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Service("equipmentService")
public class EquipmentServiceImpl implements EquipmentService {

    @Resource
    private NodeDataResolverFactory factory;

    @Resource
    private EquimentDao equimentDao;

    @Resource
    private WebSockerSender webSockerSender;

    @Resource
    private AlarmService alarmService;

    @Resource
    private AlarmListService alarmListService;

    @Override
    public void process(String equipmentNum, String data) {
        log.info("收到设备号:{},上传内容:{}", equipmentNum, data);
        JSONObject object = JSONObject.parseObject(data);
        data = object.getString("data");
        // 根据设备号获取设备类型
        Map<String, Object> map = Maps.newHashMap();
        map.put("eid", equipmentNum);
        List<Map<String, Object>> query = equimentDao.query(map);
        if(!query.isEmpty()) {
            String type = (String) query.get(0).get("type");
            EquipmentEnum equipmentEnum = EquipmentEnum.getEquipmentByType(type);
            // 解析设备节点上报的数据
            NodeDataResolver resolver = factory.getResolver(equipmentEnum);
            EquipmentDto resolve = resolver.resolve(equipmentNum, data);
            if(resolve != null) {
                // 写入预警信息表
                AtomicBoolean alarmFlag = new AtomicBoolean(false);
                Map<String, Object> search = Maps.newHashMap();
                search.put("EQ_epId", equipmentNum);
                search.put("EQ_status", 1);
                List<Alarm> alarmGroups = alarmService.query(search, null);
                alarmGroups.forEach(v -> {
                    try {
                        String alarm = CheckUtil.alarm(resolve.getEntity(), v.getAlarmConfig());
                        if(StringUtils.isNotBlank(alarm)) {
                            alarmFlag.set(true);
                            JSONObject jsonObject = JSONObject.parseObject(v.getAlarmConfig());
                            AlarmList alarmList = new AlarmList();
                            alarmList.setEpId(equipmentNum);
                            alarmList.setAlarmInfo(alarm);
                            alarmList.setHandleStatus(0);
                            alarmList.setFieldName(jsonObject.getString("field"));
                            alarmList.setFieldTitle(jsonObject.getString("title"));
                            if(StringUtils.isNotBlank(alarmList.getFieldName())) {
                                Map<String, Object> condition = Maps.newHashMap();
                                condition.put("EQ_epId", equipmentNum);
                                condition.put("EQ_fieldName", alarmList.getFieldName());
                                condition.put("GTE_createTime", Dates.format(new Date(), Dates.CHINESE_DATE_FORMAT_LINE) + " 00:00:00");
                                List<AlarmList> query1 = alarmListService.query(condition, null);
                                if(query1.isEmpty()) {
                                    alarmListService.save(alarmList);
                                }
                            } else {
                                alarmListService.save(alarmList);
                            }
                        }
                    } catch (IllegalAccessException e) {
                        log.error("设备号{},{}", equipmentNum, e);
                    }
                });
                // 保存数据到数据库
                resolver.save(resolve.getEntity(), alarmFlag.get());
                // 推送消息到前端
                webSockerSender.sendMsgToAllClient(equipmentNum, JSONObject.toJSONString(resolve.getEntity()), alarmFlag.get());
            }
        }
    }

    public List<Map<String,Object>> query(Map<String,Object> map){
        return equimentDao.query(map);
    }
    public int alarmdelete(String id){
        return equimentDao.alarmdelete(id);
    }
    public int delete(String id){
        return equimentDao.delete(id);
    }
    public int alarmParmentdelete(String id){
        return equimentDao.alarmParmentdelete(id);
    }
    public List<Map<String,Object>> queryalarmParment(Map<String,Object> map){
        return equimentDao.queryalarmParment(map);
    }
    public List<Map<String,Object>> queryalarm(Map<String,Object> map){
        return equimentDao.queryalarm(map);
    }
    public int saveAlarmParment(Map<String,Object> map){
        return equimentDao.saveAlarmParment(map);
    }
    public int editAlarmParment(Map<String,Object> map){
        return equimentDao.editAlarmParment(map);
    }
    public int saveAlarm(Map<String,Object> map){
        return equimentDao.saveAlarm(map);
    }
    public int save (Map<String,Object> map){
        return equimentDao.save(map);
    }
    public int update (Map<String,Object> map){
        return equimentDao.update(map);
    }
}
